package io.renren.common.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.net.MalformedURLException;
import java.security.InvalidParameterException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Calendar;

import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;

/**
 * @Description: 生成PDF合同工具类
 * @author liguodong
 * @date 2022年3月6日 下午5:19:32
 */
public class GeneratePdfUtil {

    //private static final String TEMPORARY_CONTRACT_HTML = "E:\\workspace\\dytc\\dytc\\seezoon-admin-server\\src\\main\\resources\\contract\\temporary.html";// 临时HTML合同，用于转PDF格式
    private static final String TEMPORARY_CONTRACT_HTML = "vast-service/vast-financial-service/src/main/resources/static/temporary.html";
    //private static final String SIMSUM_FILE = "E:\\workspace\\dytc\\dytc\\seezoon-admin-server\\src\\main\\resources\\common\\simsun.ttc";// 添加字体，解决中文支持问题
    private static final String SIMSUM_FILE = "D:\\专六\\拉取git代码\\vast-finance\\vast_service\\vast_service_backstages\\src\\main\\java\\io\\renren\\common\\font\\simsun.ttf";


    public static String GenerateContract(ContractDynamicParam param) throws Exception {
        // 生成html合同
        generateHTML(param.getTemplatePath(), param.getTemplateName(), param.getContractParam());
        // 根据html合同生成pdf合同
        generatePDF(param.getContractPath() + param.getContractName());
        // 删除临时html格式合同
        removeFile(TEMPORARY_CONTRACT_HTML);
        return param.getContractPath() + param.getContractName();
    }

    /**
     * @Description 生成html格式合同
     */
    private static void generateHTML(String templatePath, String templateName, Map<String, Object> paramMap) throws Exception {


        Configuration cfg = new Configuration();
        cfg.setDefaultEncoding("UTF-8");
        /**
         * 1.setClassForTemplateLoading(this.getClass(), "/HttpWeb");
         * 基于类路径，HttpWeb包下的framemaker.ftl文件
         * 2.setDirectoryForTemplateLoading(new File("/template"));
         * 基于文件系统,template目录下的文件
         * 3.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template");
         * 基于Servlet Context，指的是基于WebRoot下的template下的framemaker.ftl文件
         */
        cfg.setDirectoryForTemplateLoading(new File(templatePath));

        // templateName.ftl为要装载的模板
        Template template = cfg.getTemplate(templateName);

        File outHtmFile = new File(TEMPORARY_CONTRACT_HTML);

        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outHtmFile)));
        // 将参数输出到模版，并操作到HTML上
        template.process(paramMap, out);
        out.close();
    }


    private static int topValue = 10;
    private static int leftValue = 20;
    private static int rightValue = 10;
    private static int bottomValue = 10;
    private static int userSpaceWidth = 650;
    /**
     * @Description 根据html生成pdf格式合同
     */
    private static void generatePDF(String pdfUrl) throws Exception {

        try {
//            Test jt = new Test();
            //此处填写你的html文件
            String html = readFile("vast_service/vast_service_backstages/src/main/resources/static/temporary.html", "UTF-8");
            //此处填写你下载的地方
            doConversion2(html, "C:/Users/LENOVO/Desktop/贷款合同.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void doConversion2(String htmlDocument, String outputPath)
            throws InvalidParameterException, MalformedURLException,
            IOException {
        PD4ML pd4ml = new PD4ML();
        pd4ml.enableDebugInfo();
        pd4ml.setHtmlWidth(userSpaceWidth);
        pd4ml.setPageSize(PD4Constants.A4);
        pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue,
                rightValue));
//此处的classPath注意一定要获取到你放fonts的文件夹。他需要获取到你下载的字体
        String classPath = Test.class.getResource("/")+"fonts/";
        pd4ml.useTTF(classPath, true);
        pd4ml.setDefaultTTFs("SimSun", "SimSun", "SimSun");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        pd4ml.render(new StringReader(htmlDocument), baos);
        baos.close();
        File output = new File(outputPath);
        FileOutputStream fos = new FileOutputStream(output);
        fos.write(baos.toByteArray());
        fos.close();
    }

    private final static String readFile(String path, String encoding)
            throws IOException {
        File f = new File(path);
        FileInputStream is = new FileInputStream(f);
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayOutputStream fos = new ByteArrayOutputStream();
        byte buffer[] = new byte[2048];
        int read;
        do {
            read = is.read(buffer, 0, buffer.length);
            if (read > 0) {
                fos.write(buffer, 0, read);
            }
        } while (read > -1);
        fos.close();
        bis.close();
        is.close();
        return fos.toString(encoding);
    }

    /**
     * @Description 移除文件
     */
    private static void removeFile(String fileUrl) {
        File file = new File(fileUrl);
        file.delete();
    }

    public static void returnPdfStream(HttpServletResponse response, String pathName) throws Exception {
        response.setContentType("application/pdf");

        File file = new File(pathName);
        if (file.exists()) {
            FileInputStream in = new FileInputStream(file);
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[1024 * 5];
            int n;
            while ((n = in.read(b)) != -1) {
                out.write(b, 0, n);
            }
            out.flush();
            in.close();
            out.close();
        }
    }
}